/*
 * DBObjectRepresentation.java
 *
 * Created on August 1, 2007, 1:22 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.auth.service.app;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.atomojo.auth.service.db.XMLObject;
import org.infoset.xml.InfosetFactory;
import org.infoset.xml.ItemConstructor;
import org.infoset.xml.XMLException;
import org.infoset.xml.util.WriterItemDestination;
import org.milowski.db.DBObject;
import org.restlet.data.MediaType;
import org.restlet.representation.OutputRepresentation;

/**
 *
 * @author alex
 */
public class DBObjectRepresentation extends OutputRepresentation
{
   
   DBObject obj;
   boolean contents;
   public DBObjectRepresentation(MediaType type,DBObject obj)
   {
      this(type,obj,true);
   }
   
   /** Creates a new instance of DBObjectRepresentation */
   public DBObjectRepresentation(MediaType type,DBObject obj,boolean contents)
   {
      super(type);
      this.obj = obj;
      this.contents = contents;
   }
   
   public void write(OutputStream os)
      throws IOException
   {
      if (obj instanceof XMLObject) {
         OutputStreamWriter w = new OutputStreamWriter(os,getCharacterSet().toString());
         try {
            WriterItemDestination dest = new WriterItemDestination(w,getCharacterSet().toString());
            ItemConstructor constructor =InfosetFactory.getDefaultInfoset().createItemConstructor();
            dest.send(constructor.createDocument());
            ((XMLObject)obj).generate(constructor, dest,contents);
            dest.send(constructor.createDocumentEnd());
         } catch (XMLException ex) {
            throw new IOException(ex.getMessage());
         }
         w.flush();
      }
   }
   
}
